/**
 * 有三个线程，分别只能打印A，B和C
 * 要求按顺序打印ABC，打印10次
 * 输出示例：
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 */
public class Thread_2252 {
    // 计数器
   private static volatile int count = 0;
    // 定义一个单独的锁对象
    private static Object lock = new Object();

    public static void main(String[] args) {
        // 创建三个线程，并指定线程名，每个线程名分别用A,B,C表示
        Thread t1 = new Thread(() -> {
            // 循环10次
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    while (count % 3 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(Thread.currentThread().getName());
                    count++;
                    lock.notifyAll();
                }
            }
        }, "A");
        Thread t2 = new Thread(() -> {
            // 循环10次
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    while (count % 3 != 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(Thread.currentThread().getName());
                    count++;
                    lock.notifyAll();
                }
            }
        }, "B");
        Thread t3 = new Thread(() -> {
            // 循环10次
            for (int i = 0; i < 10; i++) {
                synchronized (lock) {
                    while (count % 3 != 2) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(Thread.currentThread().getName());
                    count++;
                    lock.notifyAll();
                }
            }
        }, "C");
        // 启动线程
        t1.start();
        t2.start();
        t3.start();
    }
}

